<template>
  <div class="register">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="register-ruleForm"
    >
      <el-form-item>
        <h1>注册</h1>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input v-model="ruleForm.rePassword" type="password" show-password autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()" style="width: 100%"> 注册 </el-button>
      </el-form-item>
      <el-form-item>
        <RouterLink to="/login">去登录</RouterLink>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { registerApi } from '@/api/api'
import { ElMessage } from 'element-plus'

const ruleFormRef = ref()

const ruleForm = reactive({
  username: '',
  password: '',
  rePassword: '',
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  rePassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== ruleForm.password) {
          callback(new Error('两次密码不一致！'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const submitForm = async () => {
  const response = await registerApi(ruleForm.username, ruleForm.password)
  console.log(response)
  if (response.data.code === 200) {
    ElMessage.success('注册成功')
    router.push('/login') // 注册成功后跳转到登录页面
  } else {
    ElMessage.error('注册失败')
  }
}
</script>

<style lang="scss" scoped>
.register {
  width: 100%;
  height: 100%;
  background-color: rgb(210, 210, 210);

  display: flex;
  align-items: center;
  justify-content: center;

  .register-ruleForm {
    width: 300px;
    padding: 20px;
    border-radius: 10px;
    background-color: white;
  }
}
</style>
